package com.ikingtech.framework.sdk.pay.embedded.supplier.wechat;

import com.ikingtech.framework.sdk.enums.pay.CashierSupplierEnum;
import com.ikingtech.framework.sdk.pay.embedded.supplier.CashierSupplierConfig;
import com.ikingtech.framework.sdk.pay.embedded.supplier.PayArgs;
import com.ikingtech.framework.sdk.pay.embedded.supplier.PayOrder;
import com.ikingtech.framework.sdk.utils.Tools;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.app.AppService;
import com.wechat.pay.java.service.payments.app.AppServiceExtension;
import com.wechat.pay.java.service.payments.app.model.Amount;
import com.wechat.pay.java.service.payments.app.model.CloseOrderRequest;
import com.wechat.pay.java.service.payments.app.model.PrepayRequest;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

/**
 * @author tie yan
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class WechatAppPayCashier {

    public static PayOrder prepay(PayArgs payArgs, CashierSupplierConfig config, RSAAutoCertificateConfig rsaConfig) {
        PrepayRequest request = new PrepayRequest();
        Amount amount = new Amount();
        amount.setTotal((int) (payArgs.getAmount() * 100));
        request.setAmount(amount);
        request.setMchid(config.getCustomId());
        request.setAppid(config.getAppId());
        request.setDescription(payArgs.getSubject());
        request.setNotifyUrl(config.getNotifyUrl() + "/" + CashierSupplierEnum.WECHAT_PAY.name() + "/" + payArgs.getRequestId());
        request.setOutTradeNo(payArgs.getRequestId());
        AppServiceExtension payService = new AppServiceExtension.Builder().config(rsaConfig).build();
        PayOrder payOrder = new PayOrder();
        payOrder.setRequestId(payArgs.getRequestId());
        payOrder.setPayInfo(Tools.Json.toJsonStr(payService.prepayWithRequestPayment(request)));
        return payOrder;
    }

    public static void closeOrder(String requestId, CashierSupplierConfig config, RSAAutoCertificateConfig rsaConfig) {
        CloseOrderRequest request = new CloseOrderRequest();
        request.setMchid(config.getCustomId());
        request.setOutTradeNo(requestId);
        AppService payService = new AppService.Builder().config(rsaConfig).build();
        payService.closeOrder(request);
    }
}
